<template>
  <div class="manage">

    <el-dialog
      title="考勤状态"
      :visible.sync="dialog.isShow"
    >
      <el-cascader
        v-model="dialog.status"
        :options="statusTree"
        :props="{
        value: 'code',
        label: 'message',
        children: 'children',
        checkStrictly: true,
        emitPath: false,
        expandTrigger: 'hover',
        lazy: false
        }"
        :show-all-levels="false"
        clearable
        filterable
        style="width:100%"
      >
        <template slot-scope="{ node, data }">
          <el-tag :type="data.tagType" size="mini">
            {{ data.message }}
          </el-tag>
        </template>
      </el-cascader>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.isShow = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>

    <!--操作-->
    <div style="margin-bottom: 10px">
      <el-upload v-permission="['performance:attendance:import']" :action="importApi" :headers="headers" accept="xlsx" :show-file-list="false"
                 :on-success="handleImportSuccess" :multiple="false"
                 style="display:inline-block">
        <el-button type="success" size="mini"
        >导入 <i class="el-icon-bottom"></i>
        </el-button>
      </el-upload>
      <el-button v-permission="['performance:attendance:export']" type="warning" size="mini" @click="handleExport" style="margin-left: 10px"
      >导出 <i class="el-icon-top"></i>
      </el-button>
    </div>

    <!---------------------- 搜索 ----------------------------->
    <div class="manage-header">
      <el-form label-width="auto" :model="searchForm.formData"
               :inline="true" size="mini">
        <el-form-item label="姓名" prop="name">
          <el-input
            placeholder="请输入姓名"
            v-model.trim="searchForm.formData.name"
            prefix-icon="el-icon-search"
          />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select
            placeholder="请选择部门"
            v-model="searchForm.formData.deptId"
          >
            <el-option
              v-for="option in searchForm.deptList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            value-format='yyyyMM'
            type="month"
            placeholder='请选择月份'
            v-model="searchForm.formData.month"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-permission="['performance:attendance:search']" type="primary" @click="search" size="mini">搜索 <i class="el-icon-search"/></el-button>
          <el-button type="danger" @click="reset" size="mini">重置 <i class="el-icon-refresh-left"/></el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-------------------------- 数据表格 ---------------------------------->
    <div class="common-table">
      <el-table
        :key="tableRefreshKey"
        ref="table"
        :data="table.tableData"
        height="85%"
        border
        stripe
        row-key="staffId"
        :header-cell-style="{background: '#eef1f6',color: '#606266',
        textAlign:'center',fontWeight:'bold',borderWidth:'3px'}"
      >
        <el-table-column prop="code" label="工号" min-width="125" align="center" fixed/>
        <el-table-column prop="name" label="姓名" min-width="125" align="center" fixed/>
        <el-table-column prop="deptName" label="部门" min-width="125" align="center"/>
        <el-table-column prop="phone" label="电话" min-width="125" align="center"/>
        <el-table-column
          v-for="(day, index) in dayList"
          :key="day + index"
          :label="parseDayLabel(day)"
          :width="125"
          min-width="125"
          align="center"
        >
          <template slot-scope="scope">
            <div v-permission="['performance:attendance:set']"
                 @click="changeStatus(scope.row,index)"
                 class="attendance-tag">
              <el-tag :type="scope.row.attendanceList[index].tagType"
                      class="tag-content">
                {{ scope.row.attendanceList[index].message }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pager"
        layout="total,sizes,prev,pager,next,jumper"
        :page-size="table.pageConfig.size ? table.pageConfig.size : 10"
        :page-sizes="[5, 10, 15, 20]"
        :total="table.pageConfig.total"
        :current-page.sync="table.pageConfig.current"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import { queryAll, queryByStaffIdAndDate, getImportApi, list, setAttendance, exp } from '@/api/attendance'
import { mapGetters } from 'vuex'
import { queryAll as queryAllDept } from '../../../api/dept'
import { write } from '@/utils/docs'

export default {
  name: 'Attendance',
  data () {
    return {
      cascaderProps: {
        value: 'code',
        label: 'message',
        children: 'children',
        checkStrictly: true, // 支持选择任意一级
        emitPath: false, // 只返回最后一级的值
        // 新增这两项配置
        expandTrigger: 'hover',
        lazyLeaf: true
      },
      statusTree: [], // 树形状态数据
      tableRefreshKey: 0, // 新增
      dayList: [],
      dialog: {
        isShow: false,
        data: {},
        status: '',
        statusList: [],
        originalCode: null // 新增原始状态记录
      },
      searchForm: {
        deptList: [],
        formData: {}
      },
      table: {
        tableData: [],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      dayNum: 0,
      month: ''
    }
  },
  computed: {
    ...mapGetters(['token']),
    headers () {
      return { Authorization: 'Bearer ' + this.token }
    },
    importApi () {
      return getImportApi()
    }
  },
  watch: {
    'table.tableData': function () {
      this.doLayout()
    }
  },
  methods: {
    doLayout () {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    transformTree (nodes) {
      return nodes.map(node => {
        const hasChildren = node.children && node.children.length > 0
        return {
          code: node.code,
          message: node.message,
          tagType: node.tagType,
          children: hasChildren ? this.transformTree(node.children) : null,
          disabled: this.shouldDisableNode(node.code),
          leaf: !hasChildren
        }
      })
    },
    shouldDisableNode (code) {
      // 当原始状态是请假类型（20-33）时，禁用所有非请假类型选项
      return this.dialog.originalCode >= 20 && code < 20
    },
    parseDayLabel (day) {
      if (!day) return '日期异常' // 处理空值
      return `${day.substring(4, 6)}-${day.substring(6)}`
    },
    confirm () {
      const selectedCode = this.dialog.status
      if (selectedCode === null || selectedCode === undefined) {
        this.$message.warning('请选择有效状态')
        return
      }
      this.dialog.data.status = selectedCode
      setAttendance(this.dialog.data).then(response => {
        if (response.code === 200) {
          const resData = response.data
          // 优化点：使用更精准的更新方式（移除了强制刷新逻辑）
          const targetStaff = this.table.tableData.find(
            item => item.staffId === resData.staffId
          )
          if (targetStaff) {
            const targetDay = targetStaff.attendanceList.find(
              day => day.attendanceDate === resData.attendanceDate
            )
            if (targetDay) {
              Object.assign(targetDay, resData.status)
            }
          }
          this.$message.success('修改成功')
          this.dialog.isShow = false
        }
      }).catch(error => {
        this.$message.error('更新失败：' + error.message)
      })
    },
    changeStatus (row, i) {
      this.dialog.originalCode = row.attendanceList[i].code // 记录原始状态
      // ▼▼▼ 关键修复点1：格式化日期 ▼▼▼
      const rawDate = row.attendanceList[i].attendanceDate // 原始日期应为yyyyMMdd格式
      const formattedDate = rawDate.replace(/-/g, '') // 移除所有横杠

      queryByStaffIdAndDate(row.staffId, formattedDate).then(response => { // 使用格式化后的日期
        if (response.code === 200) {
          this.dialog.data = response.data
        } else {
          this.dialog.data = {
            staffId: row.staffId,
            attendanceDate: formattedDate // ▼▼▼ 关键修复点2：使用格式化后的日期 ▼▼▼
          }
        }
      })
      this.dialog.isShow = true
      this.dialog.status = row.attendanceList[i].code
    },
    handleSizeChange (size) {
      this.table.pageConfig.size = size
      this.search()
    },
    handleCurrentChange (current) {
      this.table.pageConfig.current = current
      this.search()
    },
    search () {
      list({
        current: this.table.pageConfig.current,
        size: this.table.pageConfig.size,
        name: this.searchForm.formData.name,
        deptId: this.searchForm.formData.deptId,
        month: this.searchForm.formData.month,
        _: Date.now()
      }).then(response => {
        if (response.code === 200) {
          this.month = response.data.month
          // ▼▼▼ 强制同步更新 ▼▼▼
          this.dayList = []
          this.table.tableData = []
          this.$nextTick(() => {
            this.dayList = response.data.dayList || []
            this.table.tableData = response.data.list.map(item => ({
              ...item,
              attendanceList: JSON.parse(JSON.stringify(item.attendanceList)) // 深度克隆
            }))
            this.tableRefreshKey += 1
          })
        }
      })
    },
    reset () {
      this.searchForm.formData = {}
      this.search()
    },
    async loading () {
      try {
        // 并行请求所有数据
        const [statusRes, deptRes, listRes] = await Promise.all([
          queryAll(), // 考勤状态树
          queryAllDept(), // 部门数据
          list({ // 初始考勤列表
            current: this.table.pageConfig.current,
            size: this.table.pageConfig.size,
            name: this.searchForm.formData.name,
            deptId: this.searchForm.formData.deptId,
            month: this.searchForm.formData.month
          })
        ])

        // 处理考勤状态树
        if (statusRes.code === 200) {
          this.statusTree = this.transformTree(statusRes.data)
        } else {
          console.error('考勤状态加载失败:', statusRes.message)
        }

        // ▼▼▼ 修改后的部门数据处理 ▼▼▼
        this.searchForm.deptList = deptRes.data

        // 处理考勤列表数据
        if (listRes.code === 200) {
          this.dayList = listRes.data.dayList || []
          this.table.pageConfig.total = listRes.data.total
          this.month = listRes.data.month

          // 初始化表格数据
          this.$nextTick(() => {
            this.table.tableData = listRes.data.list.map(item => ({
              ...item,
              attendanceList: JSON.parse(JSON.stringify(item.attendanceList))
            }))
            this.tableRefreshKey += 1
          })
        } else {
          console.error('考勤列表加载失败:', listRes.message)
        }
      } catch (error) {
        console.error('初始化加载失败:', error)
        this.$message.error('数据加载失败，请稍后重试')
      } finally {
        // 确保搜索执行
        await this.$nextTick()
        this.search()
      }
    },
    handleExport () {
      const currentMonth = this.searchForm.formData.month || this.month // 优先使用搜索条件中的月份
      const filename = currentMonth.substring(0, 4) + '年' + currentMonth.substring(4) + '月考勤报表'
      exp(currentMonth, filename).then(response => {
        write(response, filename + '.xlsx')
      })
    },
    handleImportSuccess (response) {
      if (response.code === 200) {
        this.$message.success('数据导入成功！')
        this.search()
      } else {
        this.$message.error('数据导入失败！')
      }
    }
  },
  created () {
    this.loading().then(() => {
      // 初始化时若未选择月份，使用当前月份
      if (!this.searchForm.formData.month) {
        const now = new Date()
        this.searchForm.formData.month = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}`
      }
    })
  }
}

</script>
<style lang="less" scoped>
.common-table {
  height: calc(100% - 62px);
  background-color: white;
  position: relative;

  .pager {
    position: absolute;
    bottom: 20px;
    right: 20px;
  }
}
/* 在style标签内添加 */
.el-table__empty-block {
  min-width: 100% !important;
}

.el-table__body {
  width: auto !important;
}

.el-table__header-wrapper {
  z-index: 2 !important;
}
.el-cascader-menu {
  min-width: 200px;
}
.el-cascader-node__label {
  padding-left: 10px;
}
</style>
